/*
 * EYEditor.cpp
 *
 *  Created on: 31-gen-2009
 *      Author: fabrizio
 */

#include "eyeditor.h"

EYEditor::EYEditor(SceneMngr *smgr)
{
  SceneMgr = smgr;
  Device = smgr->Device;
  GUI = Device->getGUIEnvironment();
  showObjects();

  for(u32 i=0; i<EGDC_COUNT ; ++i)
    {
      SColor col = GUI->getSkin()->getColor((EGUI_DEFAULT_COLOR)i);
      col.setAlpha(248);
      GUI->getSkin()->setColor((EGUI_DEFAULT_COLOR)i, col);
    }
  GUI->getSkin()->setFont(GUI->getFont("editorres/lucida.xml"));

  SProject.Fullscreen = false;
  SProject.SpecialFX = false;

  Menu = GUI->addMenu();
  Menu->addItem(L"Project",100,true,true);
  Menu->addItem(L"Node",200,true,true);
  Menu->addItem(L"Objects",300,true,true);
  Menu->addItem(L"?",400,true,true);

  IGUIContextMenu *submenu, *submenu0;

  //0-PROJECT
  submenu = Menu->getSubMenu(0);
  submenu->addItem(L"New",110,false);
  submenu->addItem(L"Open",120);
  submenu->addSeparator();
  submenu->addItem(L"Settings",130);
  submenu->addItem(L"Variables",140,false);
  submenu->addSeparator();
  submenu->addItem(L"Quit",150);

  //1-NODE
  submenu = Menu->getSubMenu(1);
  submenu->addItem(L"New",210,false);
  submenu->addItem(L"Go to...",220,true,true);
  submenu0 = submenu->getSubMenu(1);
  for(unsigned int i = 0; i < smgr->NodeList.size(); i++)
    {
      stringc n = smgr->NodeList.at(i).c_str();
      stringw node = n.c_str();
      submenu0->addItem(node.c_str(),9901+i);
    }
  submenu->addSeparator();
  submenu->addItem(L"Properties",230);

  //2-OBJECTS
  submenu = Menu->getSubMenu(2);
  submenu->addItem(L"Add...",310,true,true);
  submenu0 = submenu->getSubMenu(0);
  submenu0->addItem(L"Patch",311);
  submenu0->addItem(L"Sound",312);
  submenu0->addItem(L"Sensor",313);
  submenu->addItem(L"Remove",320);
  submenu->addSeparator();
  submenu->addItem(L"Properties",330);

  //3-Help
  submenu = Menu->getSubMenu(3);
  submenu->addItem(L"About",410);

  Toolbar = GUI->addToolBar();
  ITexture *image;
  image = Device->getVideoDriver()->getTexture("editorres/open.png");
  Toolbar->addButton(500,0,L"Open node",image,0,false,true);
  image = Device->getVideoDriver()->getTexture("editorres/save.png");
  Toolbar->addButton(501,0,L"Save node",image,0,false,true);
  image = Device->getVideoDriver()->getTexture("editorres/node.png");
  Toolbar->addButton(502,0,L"Node settings",image,0,false,true);
  image = Device->getVideoDriver()->getTexture("editorres/add-patch.png");
  Toolbar->addButton(503,0,L"Add patch",image,0,false,true);
  image = Device->getVideoDriver()->getTexture("editorres/add-sound.png");
  Toolbar->addButton(504,0,L"Add sound",image,0,false,true);
  image = Device->getVideoDriver()->getTexture("editorres/add-sensor.png");
  Toolbar->addButton(505,0,L"Add sensor",image,0,false,true);
  image = Device->getVideoDriver()->getTexture("editorres/remove-obj.png");
  Toolbar->addButton(506,0,L"Remove object",image,0,false,true);
}

bool EYEditor::loadProjectAttr()
{
  IReadFile* rf = Device->getFileSystem()->createAndOpenFile("settings.xml");
  if (!rf)
    {
      Device->getLogger()->log("Unable to find \'settings.xml\'");
      return false;
    }
  IXMLReader* reader = Device->getFileSystem()->createXMLReader(rf);
  if (!reader)
    {
      Device->getLogger()->log("Project has not a valid XML file",
          rf->getFileName().c_str(), ELL_ERROR);
      return false;
    }
  while (reader->read())
    {
      bool endreached = false;
      const wchar_t* name = reader->getNodeName();
      switch (reader->getNodeType())
        {
      case EXN_ELEMENT_END:
        if (stringw(L"eternity") == name) endreached = true;
        return true;
        break;
      case EXN_ELEMENT:
        if (stringw(L"attributes") == name)
          {
            IAttributes* attr = Device->getFileSystem()->createEmptyAttributes(Device->getVideoDriver());
            attr->read(reader);
            SProject.Project = attr->getAttributeAsString("project").c_str();
            SProject.Resolution.Width = attr->getAttributeAsPosition2d("resolution").X;
            SProject.Resolution.Height = attr->getAttributeAsPosition2d("resolution").Y;
            SProject.Fullscreen = attr->getAttributeAsBool("fullscreen");
            SProject.SpecialFX = attr->getAttributeAsBool("specialfx");
          }
        break;
      default:
        break;
          }
       }
    return false;
}

void EYEditor::showObjects()
{
  SceneMgr->getCursor()->ScreenCursor->setVisible(false);
  for (unsigned int i = 0; i < SceneMgr->ThisNode->Sensors.size(); i++)
    {
      SceneMgr->ThisNode->getSensor(i)->setVisible(true);
    }
  for (unsigned int i = 0; i < SceneMgr->ThisNode->Sounds.size(); i++)
    {
      ITexture *sound = Device->getVideoDriver()->getTexture("sound.png");
      SceneMgr->ThisNode->getSound(i)->SoundCube->setMaterialTexture(0, sound);
      SceneMgr->ThisNode->getSound(i)->SoundCube->setVisible(true);
    }
  for (unsigned int i = 0; i < SceneMgr->ThisNode->Patches.size(); i++)
    {
      if (SceneMgr->ThisNode->getType() != ENT_PANEL)
        {
          ISceneNode *n = SceneMgr->ThisNode->getPatch(i)->PatchCube;
          ISceneNode *patch = SceneMgr->Device->getSceneManager()->addCubeSceneNode(
              1,n->getParent(), -1, n->getPosition(), n->getRotation(),n->getScale() * 1.01);
          ITexture *border = Device->getVideoDriver()->getTexture("border.png");
          patch->setMaterialTexture(0, border);
          patch->setMaterialFlag(EMF_LIGHTING, false);
          patch->setMaterialType(EMT_TRANSPARENT_ALPHA_CHANNEL);
          patch->setMaterialFlag(EMF_ZWRITE_ENABLE, true);
          patch->setMaterialFlag(EMF_ZBUFFER, false);

          patch->setMaterialFlag(EMF_WIREFRAME,true);
          patch->getMaterial(0).Thickness = 2.0;
          patch->setIsDebugObject(true);

          // LABEL section -----------------------------------------------------
          IGUIFont *font = Device->getGUIEnvironment()->getFont("fontlucida.png");
          stringw label = "patch:";
          label+=i;
          ISceneNode *parent = SceneMgr->ThisNode->getPatch(i)->PatchCube;
          ITextSceneNode *txt = SceneMgr->Device->getSceneManager()->addTextSceneNode(font,label.c_str(),SColor(255,255,0,0),parent,vector3df(0,0,49.f));
          txt->setMaterialFlag(EMF_ZWRITE_ENABLE,false);
        }
      if(SceneMgr->ThisNode->getType() == ENT_PANEL)
				{
					rect<s32> rec1 = SceneMgr->ThisNode->getPatch(i)->PatchPanel->getRelativePosition();
					rect<s32> rec = rect<s32>(1,1,rec1.getWidth()-1,rec1.getHeight()-1);
					IGUIElement *parent = SceneMgr->ThisNode->getPatch(i)->PatchPanel;
					IGUIStaticText *border = SceneMgr->Device->getGUIEnvironment()->addStaticText(L"",rec,true,false,parent);

					// LABEL section -----------------------------------------------------
					IGUIFont *font = Device->getGUIEnvironment()->getFont("fontlucida.png");
					dimension2d<u32> size = font->getDimension(L"sensor 0");
					rect<s32> pos = rect<s32>(rec.getWidth()/2 - size.Width/2,
																		rec.getHeight()/2 - size.Height/2,
																		rec.getWidth()/2 - size.Width/2 + size.Width,
																		rec.getHeight()/2 - size.Height/2 + size.Height);
					stringw label = "patch:";
					label+=i;
					IGUIStaticText *txt = SceneMgr->Device->getGUIEnvironment()->addStaticText(label.c_str(),pos,false,false,border,-1,true);
					txt->setTextAlignment(EGUIA_CENTER,EGUIA_CENTER);
				}
    }
}

void EYEditor::projectDlg()
{
  GProject.Window = GUI->addWindow(rect<s32>(64,128,240+64,320+128),true,L"Project properties");
  IGUITabControl *tabctrl =  GUI->addTabControl(rect<s32>(0,20,240,270),GProject.Window);
  tabctrl->addTab(L"Properties",0);
  tabctrl->addTab(L"Events",1);
  GUI->addButton(rect<s32>(70, 280, 170, 310),GProject.Window,1300,L"Ok");

  GUI->addStaticText(L"Title",rect<s32>(10, 10, 80, 30),false,false,tabctrl->getTab(0));
  GUI->addStaticText(L"Folder",rect<s32>(10, 40, 80, 60),false,false,tabctrl->getTab(0));
  GUI->addStaticText(L"Start node",rect<s32>(10, 70, 80, 90),false,false,tabctrl->getTab(0));
  GUI->addStaticText(L"Resolution",rect<s32>(10, 100, 80, 120),false,false,tabctrl->getTab(0));

  GProject.Title =
  GUI->addEditBox(SceneMgr->Title.c_str(),rect<s32>(80, 10, 230, 30),true,tabctrl->getTab(0),1301);
  GProject.Project =
  GUI->addEditBox(SceneMgr->Project.c_str(),rect<s32>(80, 40, 230, 60),true,tabctrl->getTab(0),1302);

  GProject.StartNode =
    GUI->addComboBox(rect<s32>(80,70,230,90),tabctrl->getTab(0),1303);
 for(unsigned int i=0; i<SceneMgr->NodeList.size(); i++)
    {
      stringc n = SceneMgr->NodeList.at(i).c_str();
      stringw node = n.c_str();
      GProject.StartNode->addItem(node.c_str());
      GProject.StartNode->setSelected(SceneMgr->StartNode);
    }

  GProject.Resolution =
    GUI->addComboBox(rect<s32>(80,100,230,120),tabctrl->getTab(0),1304);
  GProject.Resolution->addItem(L"[Defautl]800x600");
  for(s32 i = 0; i < Device->getVideoModeList()->getVideoModeCount();i++)
    {
      stringw item = "";
      item += Device->getVideoModeList()->getVideoModeResolution(i).Width;
      item += "x";
      item += Device->getVideoModeList()->getVideoModeResolution(i).Height;
      GProject.Resolution->addItem(item.c_str());

      if(SProject.Resolution == Device->getVideoModeList()->getVideoModeResolution(i))
        GProject.Resolution->setSelected(i);
    }

  GProject.Fullscreen =
  GUI->addCheckBox(SProject.Fullscreen,rect<s32>(10,130,100,150),tabctrl->getTab(0),1305,L"Full screen");
  GProject.SpecialFX =
  GUI->addCheckBox(SProject.SpecialFX,rect<s32>(10,160,100,180),tabctrl->getTab(0),1306,L"Special FX");

}

bool EYEditor::OnEvent(const SEvent & event)
{
  //Smgr->getCursor()->OnEvent(event);
  SceneMgr->updateListenerPosition(event);
  IAttributes *attr = Device->getFileSystem()->createEmptyAttributes(Device->getVideoDriver());
  position2d<s32> res;


  if (event.EventType == EET_GUI_EVENT)
    {
      s32 id = event.GUIEvent.Caller->getID();
      switch(event.GUIEvent.EventType)
      {
        case EGET_MENU_ITEM_SELECTED:
          {
          IGUIContextMenu* menu = (IGUIContextMenu*)event.GUIEvent.Caller;
          s32 id = menu->getItemCommandId(menu->getSelectedItem());
          switch(id)
          {
            case 110: // Project->New..
              break;
            case 120: //Project->Open
              break;
            case 130: // Project->Properties
              projectDlg();
              break;

            default:
              if(id > 9900)
                {
                  SceneMgr->gotoNode(id-9901,ETT_FADE,500,1);
                  Menu->getParent()->bringToFront(Menu);
                  Toolbar->getParent()->bringToFront(Toolbar);
                  showObjects();
                }
              break;
          }
          break;
          }
        case gui::EGET_BUTTON_CLICKED:
          switch(id)
          {
            case 1300:
              attr->addString("title",GProject.Title->getText());
              attr->addString("project",GProject.Project->getText());
              attr->addInt("startnode",GProject.StartNode->getSelected());
              res.X = Device->getVideoModeList()->getVideoModeResolution(GProject.Resolution->getSelected()).Width;
              res.Y = Device->getVideoModeList()->getVideoModeResolution(GProject.Resolution->getSelected()).Height;
              attr->addPosition2d("resolution",res);
              attr->addBool("fullscreen",GProject.SpecialFX->isChecked());
              attr->addBool("specialfx",GProject.SpecialFX->isChecked());

              GProject.Window->remove();
            default:
              break;
          }
        default:
          break;
      }
    }
  //CAMERA
  if (event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
    {
      Device->getSceneManager()->getActiveCamera()->setInputReceiverEnabled(
          !Device->getSceneManager()->getActiveCamera()->isInputReceiverEnabled());
    }

  return false;
}

EYEditor::~EYEditor()
{

}
